package com.googlecode.mapperdao

import exceptions.PersistException
import jdbc.Setup
import org.scalatest.FunSuite
import org.scalatest.matchers.ShouldMatchers
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

/**
 * @author kkougios
 */
@RunWith(classOf[JUnitRunner])
class ErrorsSuite extends FunSuite with ShouldMatchers
{
	val (jdbc, mapperDao, queryDao) = Setup.setupMapperDao(TypeRegistry(PersonEntity, CompanyEntity))

	test("invalid column name") {
		CommonEntities.createPersonCompany(jdbc)

		try {
			mapperDao.insert(PersonEntity, Person("test", Company("acme")))
			fail()
		} catch {
			case e: PersistException =>
				Setup.database match {
					case "postgresql" =>
						e.causes.map(_.getClass) should be(List(classOf[org.springframework.jdbc.BadSqlGrammarException], classOf[java.sql.BatchUpdateException], classOf[org.postgresql.util.PSQLException]))
					case "h2" =>
						e.causes.map(_.getClass) should be(List(classOf[org.springframework.jdbc.BadSqlGrammarException]))
					case "mysql" =>
						e.causes.map(_.getClass) should be(List(classOf[org.springframework.jdbc.BadSqlGrammarException]))
					case "sqlserver" =>
						e.causes.map(_.getClass) should be(List(classOf[org.springframework.jdbc.BadSqlGrammarException]))
					case "oracle" =>
						e.causes.map(_.getClass) should be(List(classOf[org.springframework.jdbc.BadSqlGrammarException]))
					case "derby" =>
						e.causes.map(_.getClass) should be(List(classOf[org.springframework.jdbc.BadSqlGrammarException]))
				}
		}
	}

	case class Person(name: String, company: Company)

	case class Company(name: String)

	object PersonEntity extends Entity[Int, SurrogateIntId, Person]
	{
		val id = key("id") sequence (Setup.database match {
			case "oracle" => Some("PersonSeq")
			case _ => None
		}) autogenerated (_.id)
		val name = column("nameINVALID") to (_.name)
		val company = manytoone(CompanyEntity) to (_.company)

		def constructor(implicit m) = new Person(name, company) with Stored
		{
			val id: Int = PersonEntity.id
		}
	}

	object CompanyEntity extends Entity[Int, SurrogateIntId, Company]
	{

		val id = key("id") sequence (Setup.database match {
			case "oracle" => Some("CompanySeq")
			case _ => None
		}) autogenerated (_.id)
		val name = column("name") to (_.name)

		def constructor(implicit m) = new Company(name) with Stored
		{
			val id: Int = CompanyEntity.id
		}
	}

}